using System;
using System.Windows;
using Eneter.Messaging.EndPoints.StringMessages;
using Eneter.Messaging.MessagingSystems.MessagingSystemBase;
using Eneter.Messaging.MessagingSystems.TcpMessagingSystem;

namespace Lib.Helper
{
    public class Socket
    {
        public IDuplexStringMessageSender myMessageSender { get; set;}
        public string IncomingMessage { get; set; }
        public Socket()
        {
            IDuplexStringMessagesFactory aStringMessagesFactory = new DuplexStringMessagesFactory();
            myMessageSender = aStringMessagesFactory.CreateDuplexStringMessageSender();
            myMessageSender.ResponseReceived += MessageReceived;
           
            IMessagingSystemFactory aMessaging = new TcpMessagingSystemFactory();
            IDuplexOutputChannel aDuplexOutputChannel = aMessaging.CreateDuplexOutputChannel("127.0.0.1:4502");
           
            try
            {
                myMessageSender.AttachDuplexOutputChannel(aDuplexOutputChannel);
            }catch(Exception ex)
            {
                //MessageBox.Show("Socket Server Not Ready!");
            }
           
        }

        public void SendMessage(string Message)
        {
            try
            {
                myMessageSender.SendMessage(Message);

            }catch(Exception ex)
            {
                MessageBox.Show("Client Service Socket Not Started!");
                Reconnect();

            }
            
        }

        private void MessageReceived(object sender, StringResponseReceivedEventArgs e)
        {
            IncomingMessage = e.ResponseMessage;
        }

        private void Reconnect()
        {
            IDuplexStringMessagesFactory aStringMessagesFactory = new DuplexStringMessagesFactory();
            myMessageSender = aStringMessagesFactory.CreateDuplexStringMessageSender();
            myMessageSender.ResponseReceived += MessageReceived;

            // Create TCP based messaging.
            IMessagingSystemFactory aMessaging = new TcpMessagingSystemFactory();
            IDuplexOutputChannel aDuplexOutputChannel = aMessaging.CreateDuplexOutputChannel("127.0.0.1:4502");

            try
            {
                myMessageSender.AttachDuplexOutputChannel(aDuplexOutputChannel);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Socket Server Not Ready!");
            }
        }
    }
}
